<template>
  <div class="main">
    <!-- 遮罩层 -->
    <div
      class="box1"
      v-if="maskedIsshow"
    >

      <div class="container">
        <!-- 主要内容 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          class="masked"
        >
          <div
            class="turnoff el-icon-close"
            @click="maskedIsshow=false"
          ></div>
          <div class="form-wrapper">
            <!-- 表单头部tab -->
            <el-row
              type="flex"
              justify="center"
              class="tabs"
            >
              <span
                :class="{ active: currentTab === index }"
                v-for="(item, index) in [`登录`, `注册`]"
                :key="index"
                @click="handleChangeTab(index)"
              >
                {{ item }}
              </span>
            </el-row>

            <!-- 登录功能组件 -->
            <LoginForm
              v-if="currentTab == 0"
              @postLogin='maskedIsshow=false'
            />

            <!-- 注册功能组件 -->
            <RegisterForm
              v-if="currentTab == 1"
              @successReg='currentTab=0'
            />
          </div>
        </el-row>
      </div>
    </div>

    <!-- 左边区域 -->
    <div class="left">
      <h2>发表新攻略</h2>
      <p>分享你的个人游记，让更多人看到哦</p>

      <!-- 文章标题 -->
      <input
        type="text"
        class="title"
        v-model="title"
        placeholder="请输入标题"
      >

      <!-- 富文本框 -->
      <client-only>
        <VueEditor
          @image-added="handleImageAdded"
          id="textarea"
          class="textarea"
          v-model="content"
          :editorToolbar="customToolbar"
          useCustomImageHandler
        ></VueEditor>
      </client-only>

      <!-- 搜索城市 -->
      <div class="city">
        选择城市：
        <el-autocomplete
          class="inline-input"
          v-model="city"
          :fetch-suggestions="querySearch"
          placeholder="请输入游玩城市"
          :trigger-on-focus="false"
          @select="handleSelect"
        ></el-autocomplete>
      </div>

      <!-- 功能区域 -->
      <div class="function">
        <el-button
          type="primary"
          size="mini"
          class="publish"
          @click="sendPost"
        >发布</el-button>
        或者
        <a
          href="javascript:;"
          @click="draft"
        >保存到草稿</a>
      </div>
    </div>

    <!-- 右边区域 -->
    <div class="right">
      <div class="draft">
        <h3>草稿箱({{draftList.length}})</h3>
        <div
          class="item"
          v-for="(item,index) in draftList"
          :key="index"
        >
          <p
            class="title"
            @click="reappear(item)"
          >{{item.title}}</p>
          <div class="foot">
            <div class="date">{{moment(item.date).format('YYYY-MM-DD HH:mm:ss')}}
            </div>
            <div class="f_function">
              <div
                class="compile el-icon-edit"
                @click="reappear(item)"
              ></div>
              <div
                class="del el-icon-delete"
                @click="del(index)"
              ></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import LoginForm from "@/components/user/LoginForm";
import RegisterForm from "@/components/user/RegisterForm";
import axios from "@/utils/myaxios";
import moment from "moment";
import { upload, addPost, cities } from "@/api/post.js";
export default {
  data() {
    return {
      currentTab: 0,
      maskedIsshow: false,
      baseURL: axios.defaults.baseURL,
      title: "",
      city: "",
      cityList: [],
      cityValue: "",
      draftList: [],
      content: "",
      customToolbar: [
        ["bold", "italic", "underline"],
        [{ list: "ordered" }, { list: "bullet" }],
        ["image", "code-block"],
      ],
    };
  },
  watch: {
    "$store.state.draft.draftPost": {
      handler() {
        this.draftList = this.$store.state.draft.draftPost;
      },
      immediate: true,
    },
  },
  methods: {
    moment,
    // 遮罩层的
    handleChangeTab(index) {
      this.currentTab = index;
    },
    // 删除草稿箱的文章
    del(i) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$store.commit("draft/delDraft", i);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {});
    },
    // 重现草稿箱的文章
    reappear(v) {
      this.content = v.content;
      this.title = v.title;
      this.city = v.city;
      this.$message.success("文章取出成功");
    },
    // 保存到草稿箱
    draft() {
      const form = {
        title: this.title,
        content: this.content,
        city: this.city,
        date: moment().format(),
      };
      this.$store.commit("draft/addDraft", form);
      this.$message.success("已保存到草稿箱");
      this.content = "";
      this.title = "";
      this.city = "";
    },

    // 发布文章
    async sendPost() {
      const token = this.$store.state.user.userInfo.token;
      if (!token) {
        this.$message.warning("未登录，请先登录");
        // this.$router.push({ path: "/user/login" });
        this.maskedIsshow = true;
        return;
      }
      if (this.title.trim() == "") {
        this.$message.warning("标题不能为空");
        return;
      }
      console.log();
      if (this.content.trim() == "") {
        this.$message.warning("内容不能为空");
        return;
      }
      if (this.city.trim() == "") {
        this.$message.warning("城市不能为空");
        return;
      }
      // console.log(this.cityList.indexOf(this.cityValue));
      // console.log(this.cityList);
      // console.log(this.cityValue);
      // const newList = this.cityList.map((v) => {
      //   return v.value;
      // });
      // console.log(newList);
      // if (this.newList.indexOf(this.cityValue) == -1) {
      //   this.$message.warning("请选择游玩的城市名称或输入正规的城市名称");
      //   return;
      // }
      const data = {
        content: this.content,
        title: this.title,
        city: this.city,
      };
      const res = await addPost(data, token);
      if (res.data && res.data.message == "新增成功") {
        this.$message.success("文章发布成功");
        this.content = "";
        this.title = "";
        this.city = "";
      } else {
        this.$message.error(res.data.message);
      }
    },
    // 添加图片事件
    async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      let formData = new FormData();
      formData.append("files", file);
      let res = await upload(formData);
      if (res.status == 200) {
        this.$message.success("图片上传成功");
        let url = res.data[0].url;
        Editor.insertEmbed(cursorLocation, "image", this.baseURL + url);
      }
      resetUploader();
    },

    // 获取城市列表的事件
    async querySearch(queryString, cb) {
      this.cityValue = queryString;
      const res = await cities(queryString);
      if (res) {
        const cities = res.data.data.map((v) => {
          return { ...v, value: v.name.replace("市", "") };
        });
        this.cityList = cities;
        cb(cities);
      }
    },

    // 选择城市的事件
    handleSelect(item) {
      console.log(item);
      this.city = item.name;
    },
  },
  components: {
    LoginForm,
    RegisterForm,
  },
};
</script>

<style lang="less" scoped>
.box1 {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  z-index: 999;
  .masked {
    position: relative;
    width: 1000px;
    height: 100%;
    margin: 0 auto;
    margin-top: 250px;

    .turnoff {
      position: absolute;
      top: -55px;
      right: 250px;
      width: 30px;
      height: 30px;
      border-radius: 25px;
      border: 1px solid #ccc;
      text-align: center;
      line-height: 30px;
      color: white;
      font-size: 25px;

      &:hover {
        border-color: orange;
        color: orange;
        cursor: pointer;
      }
    }

    .form-wrapper {
      width: 400px;
      margin: 0 auto;
      background: #fff;
      box-shadow: 2px 2px 0 rgba(0, 0, 0, 0.1);
      overflow: hidden;

      .tabs {
        span {
          display: block;
          width: 50%;
          height: 50px;
          box-sizing: border-box;
          border-top: 2px #eee solid;
          background: #eee;
          line-height: 48px;
          text-align: center;
          cursor: pointer;
          color: #666;

          &.active {
            color: orange;
            border-top-color: orange;
            background: #fff;
            font-weight: bold;
          }
        }
      }
    }
  }
}
.main {
  width: 1000px;
  margin: 20px auto 0;
  display: flex;
  justify-content: space-between;

  .left {
    width: 750px;

    h2 {
      font-weight: 400;
      font-size: 22px;
      margin-bottom: 10px;
    }

    p {
      font-size: 12px;
      color: #999;
      margin-bottom: 10px;
    }

    .title {
      box-sizing: border-box;
      outline: none;
      width: 100%;
      background-color: #fff;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      color: #606266;
      display: inline-block;
      height: 40px;
      line-height: 40px;
      padding: 0 15px;
      margin-bottom: 20px;

      &::-webkit-input-placeholder {
        color: #c0c4cc;
      }
    }

    /deep/#textarea {
      margin-bottom: 20px;
      height: 400px;
    }

    .city {
      margin-bottom: 20px;
    }

    .function {
      margin-bottom: 20px;
      font-size: 14px;

      .publish {
        margin-right: 10px;
      }

      a {
        color: orange;

        &:hover {
          text-decoration: underline;
        }
      }
    }
  }

  .draft {
    box-sizing: border-box;
    padding: 20px 10px;
    width: 225px;
    border: 1px solid #ccc;

    h3 {
      text-align: center;
      margin: 0 auto 20px;
    }

    .item {
      margin-top: 20px;
      .title:hover {
        color: orange;
        cursor: pointer;
      }

      .foot {
        display: flex;
        justify-content: space-between;
        margin-top: 5px;

        .date {
          font-size: 14px;
          color: #ccc;
        }

        .compile,
        .del {
          cursor: pointer;

          &:hover {
            color: orange;
          }
        }
      }
    }
  }
}
</style>